package feizhou.untils.tools; /**
 * @2016-2016年9月6日-下午4:36:39
 * @ Niklaus Mikaelson
 * @MD5Util.java
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;


/**
 * @MD5Util
 */
public class MD5Util {
    /***
     * MD5加码 生成32位md5码
     * @param inStr
     * @return
     */
    public static String toMD5Str(String inStr) {
        // 创建MessageDigest对象
        MessageDigest md5 = null;
        // 将输入数据转换为字节数组
        byte[] inputBytes = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            inputBytes = inStr.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        // 执行MD5加密
        byte[] md5Bytes = md5.digest(inputBytes);

        // 将字节数组转换为十六进制字符串
        StringBuilder hexSb = new StringBuilder();

        for (byte b : md5Bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexSb.append('0');
            }
            hexSb.append(hex);
        }
        return hexSb.toString();

    }

    /**
     * @param file
     * @param algorithm 所请求算法的名称  for example: MD5, SHA1, SHA-256, SHA-384, SHA-512 etc.
     * @return
     */
    public static String getFileMD5(File file, String algorithm) {

        if (!file.isFile()) {
            return null;
        }

        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;

        try {
            digest = MessageDigest.getInstance(algorithm);
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    /**
     * @param algorithm 所请求算法的名称  for example: MD5, SHA1, SHA-256, SHA-384, SHA-512 etc.
     * @return
     */
    public static String getFileMD5(InputStream inputStream, String algorithm) {

        if (null == inputStream) {
            return null;
        }

        MessageDigest digest = null;
        byte buffer[] = new byte[1024];
        int len;

        try {
            digest = MessageDigest.getInstance(algorithm);
            while ((len = inputStream.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    /**
     * 获取文件夹中文件的MD5值
     *
     * @param dirFile
     * @param algorithm 所请求算法的名称  for example: MD5, SHA1, SHA-256, SHA-384, SHA-512 etc.
     * @param listChild 是否递归子目录中的文件
     * @return
     */
    public static Map<String, String> getDirMD5(File dirFile, String algorithm, boolean listChild) {

        if (!dirFile.isDirectory()) {
            return null;
        }

        // <filepath,algCode>
        Map<String, String> pathAlgMap = new HashMap<String, String>();
        String algCode;
        File files[] = dirFile.listFiles();

        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory() && listChild) {
                pathAlgMap.putAll(getDirMD5(file, algorithm, listChild));
            } else {
                algCode = getFileMD5(file, algorithm);
                if (algCode != null) {
                    pathAlgMap.put(file.getPath(), algCode);
                }
            }
        }
        return pathAlgMap;
    }

    // 测试主函数  
    public static void main(String args[]) throws Exception {
        String s = new String("25370^*#%");
        System.out.println("原始：" + s);
        System.out.println("MD5后：" + toMD5Str(s));
        String str = getFileMD5(new File("D:\\image\\certificate2\\model1133.png"), "SHA-256");
        System.out.println("sha256:" + str);
    }
}
